package edu.tsinghua.oxy.engineer.service.impl;

import edu.tsinghua.oxy.common.utils.HttpUtils;
import edu.tsinghua.oxy.engineer.entity.BookInfo;
import edu.tsinghua.oxy.engineer.service.IHtmlParse;
import edu.tsinghua.oxy.engineer.service.IProxyService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sean
 * @version 1.0
 * @date 2021/7/27
 */
@Slf4j
@Service("htmlParseBook")
public class HtmlParseBook implements IHtmlParse<BookInfo> {

    @Resource
    IProxyService proxyService;

    @Resource
    HttpUtils httpUtils;

    private List<String> keyWordList = new ArrayList<>();

    {
        keyWordList.add("页数:");
        keyWordList.add("定价:");
        keyWordList.add("ISBN:");
    }


    /**
     * 解析图书列表
     * @param listUrl 列表页面url
     *
     * @return
     */
    @Override
    public List<String> parseListHtml(String listUrl) {
        List<String> bookInfoList = new ArrayList<>();
        Document document = null;
        try {
            document = Jsoup.connect(listUrl)
                    .proxy(proxyService.getProxy())
                    .userAgent(httpUtils.getAgent()).timeout(60000).get();
        } catch (IOException e) {
            log.warn("获取网页内容： 失败");
            return bookInfoList;
        }

        Elements elements = document.getElementsByClass("subject-item");
        for (Element element : elements) {
            String bookUrl = element.getElementsByTag("a").get(1).attr("href");
            bookInfoList.add(bookUrl);
        }

        return bookInfoList;
    }

    /**
     * 解析图书详情
     * @param infoUrl 详情页面url
     *
     * @return
     */
    @Override
    public BookInfo parseInfoHtml(String infoUrl) {
        log.info("图书详情url：{}", infoUrl);
        //get获取结果集
        Document document = null;
        try {
            document = Jsoup.connect(infoUrl)
                    .proxy(proxyService.getProxy())
                    .userAgent(httpUtils.getAgent()).timeout(60000).get();
        } catch (IOException e) {
            log.warn("获取网页内容： 失败 ", e);
            return null;
        }

        BookInfo bookInfo = new BookInfo();
        //获取书名
        String bookName = document.getElementById("wrapper").getElementsByTag("h1")
                .get(0).getElementsByTag("span").text();
        bookInfo.setBookName(bookName);

        //获取作者
        Element info = document.getElementById("info");
        String author = info.getElementsByTag("a").get(0).text();
        bookInfo.setAuthor(author);

        List<Node> infos = info.childNodes();

        boolean isNeed = false;
        String keyName = "";
        Map<String, String> infoMap = new HashMap<>(5);
        for (Node node : infos) {
            //标记需要的信息
            if(node instanceof Element && keyWordList.contains(((Element) node).text().trim())){
                isNeed = true;
                keyName = ((Element) node).text().trim();
                continue;
            }

            if("".equals(node.outerHtml().trim())){
                continue;
            }

            if(isNeed){
                infoMap.put(keyName, node.outerHtml().trim());
                keyName = "";
                isNeed = false;
            }
//            log.info(node.outerHtml().trim());
        }

        bookInfo.setPageTotal(infoMap.get(keyWordList.get(0)));
        bookInfo.setPrice(infoMap.get(keyWordList.get(1)));
        bookInfo.setIsbn(infoMap.get(keyWordList.get(2)));

        //获取评分
        String score = document.getElementsByClass("rating_num").text();
        bookInfo.setScore(score);

        //获取封面图片
        String coverUrl = document.getElementsByClass("nbg").attr("href");
        bookInfo.setCoverUrl(coverUrl);

        return bookInfo;
    }


}
